package com.xiaoyu.base.dao;

import androidx.room.Dao;
import androidx.room.Insert;
import androidx.room.Query;
import androidx.room.Transaction;
import com.xiaoyu.base.entity.AreaEntity;
import com.xiaoyu.base.model.AreaBaseModel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static androidx.room.OnConflictStrategy.REPLACE;

@Dao
public abstract class AreaDao {

    public static final String NATIONAL_CODE_CHINA = "cn";

    @Insert(onConflict = REPLACE)
    public abstract void upsert(AreaEntity entity);

    @Insert(onConflict = REPLACE)
    public abstract void upsertAll(List<AreaEntity> entityList);

    @Query("DELETE FROM `area`")
    public abstract void deleteAll();

    @Query("SELECT * FROM `area` WHERE `superiorName` = :superiorName AND `level` = :level ")
    public abstract List<AreaEntity> loadArea(String superiorName, int level);

    @Transaction
    public void fetch(List<AreaEntity> entityList) {
        deleteAll();
        upsertAll(entityList);
    }

    public List<AreaBaseModel> loadAreaList() {
        List<AreaBaseModel> provinceModelList = new ArrayList<>();
        List<AreaEntity> provinceList = new ArrayList<>(loadArea(NATIONAL_CODE_CHINA, 1));
        for (AreaEntity province : provinceList) {

            List<AreaBaseModel> cityModelList = new ArrayList<>();
            List<AreaEntity> cityList = new ArrayList<>(loadArea(province.getName(), 2));
            for (AreaEntity city : cityList) {

                List<AreaBaseModel> countyModelList = new ArrayList<>();
                List<AreaEntity> countyList = new ArrayList<>(loadArea(city.getName(), 3));
                for (AreaEntity county : countyList) {

                    AreaBaseModel countyModel = new AreaBaseModel(county.getName(), Collections.<AreaBaseModel>emptyList());
                    countyModelList.add(countyModel);
                }

                AreaBaseModel cityModel = new AreaBaseModel(city.getName(), countyModelList);
                cityModelList.add(cityModel);
            }

            AreaBaseModel provinceModel = new AreaBaseModel(province.getName(), cityModelList);
            provinceModelList.add(provinceModel);
        }
        return provinceModelList;
    }
}
